//
//  ZDStatus.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/11/2.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDStatus.h"
#import "MJExtension.h"
#import "ZDNetworkTool.h"
#import "ZDUserAccount.h"
#import <SDWebImage/SDWebImageManager.h>

extern NSString *const NormalCellIdentifier;
extern NSString *const ForwardCellIdentifier;

@implementation ZDStatus


/**
*  加载微博数据  通过回调告诉调用者(控制器) 结果 调用者再做一些处理，不需要返回值
*
*  @param since_id     若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
*  @param max_id       若指定此参数，则返回ID小于或等于max_id的微博，默认为0
*  @param successBlock successBlock 成功回调
*  @param failureBlock failureBlock 失败回调
*/
+ (void)loadStatusesWithSince_id:(int64_t)since_id max_id:(int64_t)max_id success:(void (^)(NSArray *result))successBlock failure:(void (^)(NSError *error))failureBlock
{
    [[ZDNetworkTool sharedInstance] loadStatusesWithAccess_token:[ZDUserAccount loadUserAccount].access_token since_id:since_id max_id:max_id success:^(id responseObject) {
        
//        ZDLog(@"responseObject = %@", responseObject);
        
        NSDictionary *dict = (NSDictionary *)responseObject;
        
        NSArray *statusesArr = dict[@"statuses"];
        
        //字典转模型
        NSMutableArray *result = [ZDStatus objectArrayWithKeyValuesArray:statusesArr];
        
        //缓存图片
        [self cacheImage:result success:successBlock failure:failureBlock];
        
    } failure:^(NSError *error) {
        
        failureBlock(error);
    }];
}

/**
 *  缓存微博模型中的配图图片
 */
+ (void)cacheImage:(NSArray *)statuses success:(void (^)(NSArray *result))successBlock failure:(void (^)(NSError *error))failureBlock
{
    //创建任务组
    dispatch_group_t group = dispatch_group_create();
    
    if (!statuses)
    {
        return;
    }
    
    for (ZDStatus *status in statuses)
    {
        if (!status.pictureURLs)
        {
            continue;
        }
        
        //只有一张图片
        if (status.pictureURLs.count == 1)
        {
            NSURL *url = status.pictureURLs.firstObject;
            
            //进组
            dispatch_group_enter(group);
            
            //缓存图片
            [[SDWebImageManager sharedManager] downloadImageWithURL:url options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                
                //离开组
                dispatch_group_leave(group);
                
                if (error)
                {
//                    ZDLog(@"下载图片失败:%@", error);
                    
                    return;
                }
                
                //下载图片成功
//                ZDLog(@"下载图片成功:%@", imageURL);
                
//                ZDLog(@"%@", status.largePictureURLs);
            }];
        }
    }
    
    //当所有组任务都执行完毕后通知调用
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
//        ZDLog(@"所有图片缓存完毕");
        
        //将结果告诉调用者
        successBlock(statuses);
    });
}

/**
 *  返回微博配图URL数组
 */
- (NSArray *)storedPictureURLs
{
    if (!_pic_urls)
    {
        return nil;
    }
    
    NSMutableArray *URLArr = [NSMutableArray array];
    
    for (NSDictionary *dict in _pic_urls)
    {
        NSString *urlString = dict[@"thumbnail_pic"];
        
        NSURL *url = [NSURL URLWithString:urlString];
        
        [URLArr addObject:url];
    }
    
    return URLArr;
}

/**
 *  返回微博配图大图URL数组
 */
- (NSArray *)storedLargePictureURLs
{
    if (!_pic_urls)
    {
        return nil;
    }
    
    NSMutableArray *URLArr = [NSMutableArray array];
    
    for (NSDictionary *dict in _pic_urls)
    {
        NSString *urlString = dict[@"thumbnail_pic"];
        
        NSString *largeUrlString = [urlString stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"large"];
        
        NSURL *url = [NSURL URLWithString:largeUrlString];
        
        [URLArr addObject:url];
    }
    
    return URLArr;
}


///返回微博配图URL数组
- (NSArray *)pictureURLs
{
    if (self.retweeted_status)
    {
        return self.retweeted_status.storedPictureURLs;
    }
    else
    {
        return self.storedPictureURLs;
    }
}

///返回微博配图大图URL数组
- (NSArray *)largePictureURLs
{
    if (self.retweeted_status)
    {
        return self.retweeted_status.storedLargePictureURLs;
    }
    else
    {
        return self.storedLargePictureURLs;
    }
}


- (NSString *)identifier
{
    return self.retweeted_status ? ForwardCellIdentifier : NormalCellIdentifier;
}


///重写KVC 拦截属性赋值
- (void)setValue:(id)value forKey:(NSString *)key
{
    if ([key isEqualToString:@"source"])
    {
        _source = [self linkSourceWithString:value];
        
        return;
    }
    
    [super setValue:value forKey:key];
}


///截取微博来源
- (NSString *)linkSourceWithString:(NSString *)string
{
    NSString *pattern = @">(.*?)</a>";
    
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
    
    NSTextCheckingResult *result = [regular firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
    
    //    NSLog(@"%ld", result.numberOfRanges);
    
    return [string substringWithRange:[result rangeAtIndex:1]];
}


- (NSString *)description
{
    NSArray *array = @[@"created_at", @"id", @"text", @"source", @"pic_urls", @"user", @"retweeted_status"];
    
    return [NSString stringWithFormat:@"%@", [self dictionaryWithValuesForKeys:array]];
}


@end
